<template>
    <a-modal
            :get-container="getContainer"
            :visible="visible"
            :width="850"
            :confirmLoading="loading"
            @ok="handleSubmit"
            @cancel="() => {resetFields();$emit('cancel');}"
            centered
    >
        <!-- header -->
        <a-divider orientation="left">
            <b>编辑${view.entityComment}</b>
        </a-divider>
        <!-- form -->
        <a-spin :spinning="loading">
            <a-form
                    name="model-form"
                    layout="horizontal"
                    :model="entityRef"
                    :rules="rulesRef"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol"
            >
                <a-row type="flex" justify="start">
        <#assign view_index = 0>
        <#list view.propertyList as property>
            <#if (!property.isPrimaryKey()
            && property.propertyName != "id"
            && property.propertyName != "vcid"
            && property.propertyName != "createDate"
            && property.propertyName != "createOperatorId"
            && property.propertyName != "lastUpdateDate"
            && property.propertyName != "lastUpdateOperatorId"
            && property.propertyName != "modifyAble"
            && property.propertyName != "valid")>
                <#if property.isSimpleValueType()>
                    <a-col :xs="24" :sm="24" :md="12">
                        <#if property.propertyComment??>
                        <a-form-item label="${property.propertyComment}" name="${property.columnName}">
                        <#else >
                        <a-form-item label="${property.propertyName}" name="${property.columnName}">
                        </#if>
                        <#if (property.propertyName == "parentId")>
                            <a-select
                                    v-model:value="entityRef.${property.propertyName}"
                                    placeholder="请选${property.propertyName}"
                                    style="width: 100%"
                                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                    :options="${view.entityTypeSimpleName}TreeData"
                                    :field-names="{label: 'name', value: 'id'}"
                            />
                        <#elseif property.propertyTypeSimpleName == 'boolean' || property.propertyTypeSimpleName == 'Boolean'>
                             <a-radio-group
                                     v-model:value="entityRef.${property.propertyName}"
                                     name="radioGroup"
                                     :options="[{ label: '是', value: true },{ label: '否', value: false },]"
                             />

                        <#elseif property.isEnum()>
                            <a-select
                                    v-model:value="entityRef.${property.propertyName}"
                                    placeholder="请选择${property.propertyName}"
                                    style="width: 100%"
                                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                                    :options="${property.propertyName}Options"
                            />
                        <#elseif  property.propertyTypeSimpleName == 'Date'>
                            <a-input v-model:value="entityRef.${property.propertyName}" />
                        <#else>
                            <a-input v-model:value="entityRef.${property.propertyName}" />
                        </#if>
                    </a-form-item>
                    </a-col>
                <#else>
                    <a-col :xs="24" :sm="24" :md="12">
                        <#if property.propertyComment??>
                            <a-form-item label="${property.propertyComment}" name="${property.columnName}">
                                <a-input v-model:value="entityRef.${property.columnName}" />
                            </a-form-item>
                        <#else>
                             <a-form-item label="${property.columnName()}" name="${property.columnName}">
                                 <a-input v-model:value="entityRef.${property.columnName}" />
                             </a-form-item>
                        </#if>
                    </a-col>
                </#if>
                <#assign view_index = view_index + 1 >
            </#if>
        </#list>
                </a-row>
            </a-form>
        </a-spin>
    </a-modal>
</template>

<script lang="ts">
<#list view.propertyList as property>
    <#if (property.propertyName == "parentId")>
import type { TreeSelectProps } from 'ant-design-vue';
    </#if>
    <#if property.isEnum()>
import { queryList as queryEnumList } from '@/api/basicdata/basic_data_enum';
    </#if>
</#list>
import { Form } from 'ant-design-vue';
import type { RuleObject } from 'ant-design-vue/lib/form';
import type { PropType } from 'vue';
import { toRaw, defineComponent, ref, reactive, watchEffect } from 'vue';
import { validatorRemoteWrap, treeSelectListWrap, updateHandlerWrap } from '@/utils/commons';
import type { ${view.entityTypeSimpleName} } from '@/api/${view.basePackageFileName}/${view.entityVueName}';
import { exists, queryList, ,update, findById } from '@/api/${view.basePackageFileName}/${view.entityVueName}';

const formLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 4 },
        md: { span: 4 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
        md: { span: 12 },
    },
};
export interface UpdateParams {
    id: string,
    [key:string]: any,
}
export const pageContextProps = {
     getContainer: {
         type: Function as PropType<() => HTMLElement>,
         default: () => null,
     },
     visible: {
         type: Boolean,
         required: true,
     },
     params: {
        type: Object as PropType<UpdateParams>,
        default: () => null,
    },
};


export default defineComponent({
        name: 'Update${view.entityTypeSimpleName}',
        props: { ...pageContextProps },
        emits: ['ok', 'cancel'],
        setup(props, { emit }) {
<#list view.propertyList as property>
    <#if property.isEnum()>
        const ${property.propertyName}Options = ref<SelectProps['options']>([]);
        queryEnumList('${property.propertyName}').then((res) => {
            res.forEach((d) => {
                ${property.propertyName}Options.value.push({
                    label: d.name,
                    value: d.key,
                });
            });
        });
    </#if>
</#list>

    const loading = ref(false);
    //定制逻辑：初始化数据结构
    const initValues = () =>
    ({
    <#list view.propertyList as property>
        <#if (property.propertyName == "parentId")>
            parentId:undefined;
        <#else>
            <#if property.isSimpleValueType()>
                <#if property.propertyTypeSimpleName == 'boolean'
                || property.propertyTypeSimpleName == 'Boolean'>
                    ${property.propertyName}: true;
                <#else>
                    ${property.propertyName}:'';
                </#if>
            <#else>
                ${property.propertyName}:'';
            </#if>
        </#if>
    </#list>
    } as ${view.entityTypeSimpleName});
    const entityRef = reactive<${view.entityTypeSimpleName}>(initValues());
    const rulesRef = reactive({
        //注意如果数据类型不相同，一定要指定数据类型 `type` 否则会校验失败
    <#list view.propertyList as property>
        <#if (property.propertyName == "code")>
            code: [{ message: '编码不能为空', required: true, trigger: 'blur' },
                {
                    message: '编码已经存在',
                    validator: validatorRemoteWrap(exists, value => {
                        const params = {};params['code'] = value;
                        return params;
                    }),
                    trigger: 'blur',
                },],
        </#if>
        <#if (property.propertyName == "name")>
            name: [{ message: '名称不能为空', required: true, trigger: 'blur' }],
        </#if>
        <#if (property.propertyName == "type")>
             type: [{ message: '类型不能为空', required: true, trigger: 'blur' }],
        </#if>
    </#list>
    } as { [key: string]: Array<RuleObject> });
        //监听入参变化，当父组件传入参数动态变化后，子组件需响应变化
        watchEffect(() => {
            if (props.visible) {
            if (props.visible) {
                onLoadSuccess();
            }
        }
    });

    const { resetFields, validate } = Form.useForm(entityRef, rulesRef);
    const updateHandler = updateHandlerWrap(add, '${view.entityComment}', props.getContainer);
    const handleSubmit = (e: Event) => {
        e.preventDefault();
        loading.value = true;
        validate()
             .then(() => {
                const data = toRaw(entityRef);
                console.log(data);
                updateHandler(data, data.name)
                    .then(res => {
                        loading.value = false;
                        emit('ok', res);
                        resetFields();
                    })
                    .catch(errorMessage => {
                        loading.value = false;
                        console.log('error', errorMessage);
                    });
             })
            .catch(err => {
                console.log('error', err);
                loading.value = false;
            });
    };
<#list view.propertyList as property>
    <#if (property.propertyName == "parentId")>
        //加载上级组织机构树型列表
        const ${view.entityTypeSimpleName}TreeData = ref<TreeSelectProps['treeData']>([]);
        const treelist = treeSelectListWrap(queryList);
        const queryParams = {};
        queryParams['valid'] = true;
    </#if>
</#list>
        //当页面被打开的时候调用逻辑
        const onLoadSuccess = () => {
            <#list view.propertyList as property>
                <#if (property.propertyName == "parentId")>
                    treelist(queryParams).then(roots => {
                       ${view.entityTypeSimpleName}TreeData.value = [...roots];
                    });
                    //设置父级id
                    entityRef.parentId = props.params.parentId;
                </#if>
            </#list>

            //设置父级id
            findById(props.params.id).then((res) => {
        <#list view.propertyList as property>
            <#if property.isSimpleValueType()>
                entityRef.${property.propertyName} = res.${property.propertyName};
            </#if>
        </#list>
            });
        };
        return {
                ...formLayout,
                loading,
                entityRef,
                rulesRef,

                resetFields,
                handleSubmit,

    <#list view.propertyList as property>
        <#if (property.propertyName == "parentId")>
                ${view.entityTypeSimpleName}TreeData,
        </#if>
        <#if property.isEnum()>
            ${property.propertyName}Options,
        </#if>
    </#list>
        };
    },
    components: {},
});
</script>